﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.CardAcct.Interfaces;
using PARK.CardAcct.Entitys.Dto.employee;
using PARK.System.Interfaces.Permission;
using System.Text;
using PARK.CardAcct.Entitys;
using PARK.CardAcct.Entitys.Dto.Wechat;
using Microsoft.AspNetCore.Authorization;
using KYSharp.SM;
using PARK.CardAcct.Entitys.Dto;
using PARK.CardAcct.Entitys.Dto.EmployeeWechat;
using System.IO;
using Newtonsoft.Json;
using PARK.CardAcct.Entitys.Dto.EmployeeFace;
using PARK.BussinCache.Interfaces;
using Newtonsoft.Json.Linq;
using uni.ubi.open.sdk.Model;
using System.Text.RegularExpressions;
using JNPF.Logging;
using PARK.Common.Helper;
using System.Data;

namespace PARK.CardAcct.Employee
{
    /// <summary>
    /// 小程序用户
    /// </summary>
    [ApiDescriptionSettings(Tag = "Wechat", Name = "EmployeeUser", Order = 200)]
    [Route("api/wechat/[controller]")]
    public class EmployeeUserService : IWechatUserService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EmployeeEntity> _baseEmployeeRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IOrganizeService _organizeService; // 机构表仓储
        private readonly IUniubiSdkRepository _uniubiSdkRepository;

        /// <summary>
        /// 初始化一个<see cref="EmployeeUserService"/>类型的新实例
        /// </summary>
        public EmployeeUserService(
            ISqlSugarRepository<EmployeeEntity> baseEmployeeRepository,
            IUserManager userManager,
            IOrganizeService organizeService,
            IUniubiSdkRepository uniubiSdkRepository)
        {
            _baseEmployeeRepository = baseEmployeeRepository;
            _db = _baseEmployeeRepository.Context;
            _userManager = userManager;
            _organizeService = organizeService;
            _uniubiSdkRepository = uniubiSdkRepository;
        }

        #region 挂失操作
        /// <summary>
        /// 挂失操作
        /// </summary>
        /// <returns></returns>
        [HttpGet("lossState")]
        public async Task<LossEmployeeStateOutput> lossState()
        {
            var _Ret = 0;
            var _Msg = "";
            try
            {
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
                {
                    var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == userInfo.EmployeeId);
                    if (entity != null)
                    {
                        if (entity.AccStatus == 1) //可挂失
                        {
                            #region 执行挂失
                            _db.BeginTran();//开启事务
                            //修改账户状态
                            var Paras = new List<SugarParameter>();
                            StringBuilder dbSql = new StringBuilder();
                            dbSql.Append("update base_employee set ");
                            dbSql.AppendFormat("AccStatus=3,LossAccDate='{0}',EmpUpdate='{0}',IsNeedDel=1 ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            dbSql.AppendFormat(" where EmployeeId='{0}'", userInfo.EmployeeId);
                            var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                            if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
                            //写入日志
                            var _EmployeeLogEntity = new EmployeeLogEntity();
                            _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                            _EmployeeLogEntity.Create();
                            _EmployeeLogEntity.LogKind = 2;
                            _EmployeeLogEntity.LogKindName = "挂失";
                            _EmployeeLogEntity.JobNo = entity.JobNum;
                            _EmployeeLogEntity.ReallName = entity.RealName;
                            _EmployeeLogEntity.CardNo = entity.CardNo;
                            _EmployeeLogEntity.NewCardNo = entity.CardNo;
                            _EmployeeLogEntity.Summary = "通过小程序,自助挂失";
                            var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                            if (!(tisOk > 0))
                            {
                                throw PARKException.Oh(ErrorCode.COM1000);
                            }
                            else
                            {
                                #region 写入人员同步任务
                                var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                                //获取此卡类型对应的消费机
                                var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                                _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                                var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                                if (_MachineList != null && _MachineList.Rows.Count > 0)
                                {
                                    for (int i = 0; i < _MachineList.Rows.Count; i++)
                                    {
                                        var MachEye = new MachineEmployeeEntity();
                                        MachEye.Create();
                                        MachEye.EmployeeId = entity.EmployeeId;
                                        MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                        MachEye.EvtType = -1; //删除                                    
                                        MachEye.TaskStatus = 0; //待执行
                                        MachEye.TaskDate = DateTime.Now;
                                        MachEye.CompanyId = entity.CompanyId;
                                        MachEye.CompanyName = entity.CompanyName;
                                        _MachineEmployeeList.Add(MachEye);
                                    }
                                    if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                                    {
                                        isOk = await _db.Insertable(_MachineEmployeeList).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                                    }
                                }
                                #endregion
                            }
                            //关闭事务
                            _db.CommitTran();
                            #endregion

                            _Ret = 1;
                            _Msg = "挂失操作成功";
                        }
                        else if (entity.AccStatus == 3)
                        {
                            //已挂失
                            _Ret = 0;
                            _Msg = "已挂失,无需重复操作";
                        }
                        else
                        {
                            _Ret = 0;
                            _Msg = "账户状态异常,不可挂失";
                        }
                    }
                    else
                    {
                        _Ret = 0;
                        _Msg = "挂失卡户不存在";
                    }
                }
                else
                {
                    _Ret = 0;
                    _Msg = "没有此功能权限";
                }
            }
            catch (Exception ex)
            {
                _Ret = 0;
                _Msg = "执行异常";
                //回滚事务
                _db.RollbackTran();
                throw PARKException.Oh(ErrorCode.COM1002);
            }
            return new LossEmployeeStateOutput()
            {
                Ret = _Ret,
                Msg = _Msg
            };
        }
        #endregion

        #region 解除挂失操作
        /// <summary>
        /// 解除挂失操作
        /// </summary>
        /// <returns></returns>
        [HttpGet("RevlossState")]
        public async Task<LossEmployeeStateOutput> RevlossState()
        {
            var _Ret = 0;
            var _Msg = "";
            try
            {
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
                {
                    var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == userInfo.EmployeeId);
                    if (entity != null)
                    {
                        if (entity.AccStatus == 3) //可挂失
                        {
                            #region 执行解除
                            _db.BeginTran();//开启事务
                            //修改账户状态
                            var Paras = new List<SugarParameter>();
                            StringBuilder dbSql = new StringBuilder();
                            dbSql.Append("update base_employee set ");
                            dbSql.AppendFormat("AccStatus=1,LossAccDate=null,EmpUpdate='{0}',IsNeedDel=0", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            dbSql.AppendFormat(" where EmployeeId='{0}'", userInfo.EmployeeId);
                            var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                            if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
                            //写入日志
                            var _EmployeeLogEntity = new EmployeeLogEntity();
                            _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                            _EmployeeLogEntity.Create();
                            _EmployeeLogEntity.LogKind = 3;
                            _EmployeeLogEntity.LogKindName = "解挂";
                            _EmployeeLogEntity.CardNo = entity.CardNo;
                            _EmployeeLogEntity.NewCardNo = entity.CardNo;
                            _EmployeeLogEntity.JobNo = entity.JobNum;
                            _EmployeeLogEntity.ReallName = entity.RealName;
                            _EmployeeLogEntity.Summary = "通过小程序,自助解除挂失";
                            var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                            if (!(tisOk > 0))
                            {
                                throw PARKException.Oh(ErrorCode.COM1000);
                            }
                            else
                            {
                                #region 写入人员同步任务
                                var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                                //获取此卡类型对应的消费机
                                var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                                _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                                var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                                if (_MachineList != null && _MachineList.Rows.Count > 0)
                                {
                                    for (int i = 0; i < _MachineList.Rows.Count; i++)
                                    {
                                        var MachEye = new MachineEmployeeEntity();
                                        MachEye.Create();
                                        MachEye.EmployeeId = entity.EmployeeId;
                                        MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                        MachEye.EvtType = 1; //新增                                    
                                        MachEye.TaskStatus = 0; //待执行
                                        MachEye.TaskDate = DateTime.Now;
                                        MachEye.CompanyId = entity.CompanyId;
                                        MachEye.CompanyName = entity.CompanyName;
                                        _MachineEmployeeList.Add(MachEye);
                                    }
                                    if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                                    {
                                        isOk = await _db.Insertable(_MachineEmployeeList).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                                    }
                                }
                                #endregion
                            }
                            //关闭事务
                            _db.CommitTran();
                            #endregion

                            _Ret = 1;
                            _Msg = "解除挂失操作成功";
                        }
                        else
                        {
                            _Ret = 0;
                            _Msg = "未挂失,无需解除挂失";
                        }
                    }
                    else
                    {
                        _Ret = 0;
                        _Msg = "解除挂失卡户不存在";
                    }
                }
                else
                {
                    _Ret = 0;
                    _Msg = "没有此功能权限";
                }
            }
            catch (Exception ex)
            {
                _Ret = 0;
                _Msg = "执行异常";
                //回滚事务
                _db.RollbackTran();
                throw PARKException.Oh(ErrorCode.COM1002);
            }
            return new LossEmployeeStateOutput()
            {
                Ret = _Ret,
                Msg = _Msg
            };
        }
        #endregion

        #region 小程序用户认证
        /// <summary>
        /// 小程序用户认证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("AuthUser")]
        [AllowAnonymous]
        public async Task<dynamic> AuthUser([FromQuery] AuthUserInput input)
        {
            setlog("小程序用户认证->AuthUser:" + JsonConvert.SerializeObject(input));

            if (string.IsNullOrEmpty(input.openid))
            {
                return new { authcode = 0, authmsg = "未传入用户OpenId" };
            }
            if (!string.IsNullOrEmpty(input.companyId))
            {
                #region 按单位认证
                if (!string.IsNullOrEmpty(input.mobilephone) && input.mobilephone.Length > 0)
                {
                    //加密手机号
                    SM4Utils sm4 = new SM4Utils();
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    var MobilePhoneSf = sm4.Encrypt_ECB(input.mobilephone);
                    var emp = await _db.Queryable<EmployeeEntity>().Where(p => p.MobilePhoneSf.Equals(MobilePhoneSf) && p.CompanyId == input.companyId && p.DeleteMark == 0).FirstAsync();
                    if (emp != null)
                    {
                        var _wechat = await _db.Queryable<EmployeeWechatEntity>().Where(p => p.EmployeeId == emp.EmployeeId && p.OpenId != input.openid).FirstAsync();
                        if (_wechat != null)
                        {
                            return new { authcode = 3, authmsg = "您的账号已绑别的微信,请核实" };
                        }
                        else
                        {
                            var wechat = await _db.Queryable<EmployeeWechatEntity>().Where(p => p.OpenId.Equals(input.openid) && p.CompanyId.Equals(input.companyId)).FirstAsync();
                            if (wechat == null)
                            {
                                wechat = new EmployeeWechatEntity()
                                {
                                    OpenId = input.openid, //微信公众号openId
                                };
                                wechat.Create();
                                wechat.IsMain = 1;
                                wechat.WId = YitIdHelper.NextId().ToString();
                                wechat.IsDeleted = 0;
                                wechat.Avatar = input.avatar;
                                wechat.Nickname = input.nickname;
                                wechat.Sex = emp.Gender;
                                wechat.EmployeeId = emp.EmployeeId;
                                wechat.JobNum = emp.JobNum;
                                wechat.RealName = emp.RealName;
                                wechat.MobilePhoneSf = MobilePhoneSf;
                                wechat.IsAudit = 1;
                                wechat.AuditDate = DateTime.Now;
                                wechat.AuditUser = "sys";
                                wechat.AuditUserName = "系统服务";
                                wechat.CompanyId = emp.CompanyId;
                                wechat.CompanyName = emp.CompanyName;
                                await _db.Insertable(wechat).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                            }
                            else
                            {
                                wechat.Avatar = input.avatar;
                                wechat.Nickname = input.nickname;
                                wechat.Sex = emp.Gender;
                                wechat.EmployeeId = emp.EmployeeId;
                                wechat.JobNum = emp.JobNum;
                                wechat.RealName = emp.RealName;
                                wechat.MobilePhoneSf = MobilePhoneSf;
                                wechat.IsAudit = 1;
                                wechat.AuditDate = DateTime.Now;
                                wechat.AuditUser = "sys";
                                wechat.AuditUserName = "系统服务";
                                wechat.CompanyId = emp.CompanyId;
                                wechat.CompanyName = emp.CompanyName;
                                await _db.Updateable(wechat).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                            }
                            var Paras = new List<SugarParameter>();
                            StringBuilder _dbSql = new StringBuilder("update base_employee set Isauth=1,");
                            _dbSql.AppendFormat("Authtimes='{0}',", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            _dbSql.AppendFormat("wId='{0}'", wechat.WId);
                            _dbSql.AppendFormat(" where EmployeeId='{0}'", emp.EmployeeId);
                            await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);
                            return new { authcode = 1, authmsg = "认证成功", empentity = emp };
                        }
                    }
                    else
                    {
                        return new { authcode = 2, authmsg = "手机号与预留手机号不一致" };
                    }
                }
                else
                {
                    return new { authcode = 0, authmsg = "输入认证手机号有误" };
                }
                #endregion
            }
            else
            {
                setlog("小程序用户认证->AuthUser->原认证方法:用户OpenId:" + input.openid);

                #region 原认证方法
                var wechat = await _db.Queryable<EmployeeWechatEntity>().Where(p => p.OpenId.Equals(input.openid)).FirstAsync();
                if (!string.IsNullOrEmpty(input.mobilephone) && input.mobilephone.Length > 0)
                {
                    //加密手机号
                    SM4Utils sm4 = new SM4Utils();
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    var MobilePhoneSf = sm4.Encrypt_ECB(input.mobilephone);
                    var emp = await _db.Queryable<EmployeeEntity>().Where(p => p.MobilePhoneSf.Equals(MobilePhoneSf) && p.DeleteMark == 0).FirstAsync();
                    if (emp != null)
                    {
                        var _wechat = await _db.Queryable<EmployeeWechatEntity>().Where(p => p.EmployeeId == emp.EmployeeId && p.OpenId != input.openid).FirstAsync();
                        if (_wechat != null)
                        {
                            return new { authcode = 3, authmsg = "您的账号已绑别的微信,请核实" };
                        }
                        else
                        {
                            wechat.Avatar = input.avatar;
                            wechat.Nickname = input.nickname;
                            wechat.Sex = emp.Gender;
                            wechat.EmployeeId = emp.EmployeeId;
                            wechat.JobNum = emp.JobNum;
                            wechat.RealName = emp.RealName;
                            wechat.MobilePhoneSf = MobilePhoneSf;
                            wechat.IsAudit = 1;
                            wechat.AuditDate = DateTime.Now;
                            wechat.AuditUser = "sys";
                            wechat.AuditUserName = "系统服务";
                            wechat.CompanyId = emp.CompanyId;
                            wechat.CompanyName = emp.CompanyName;
                            await _db.Updateable(wechat).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

                            var Paras = new List<SugarParameter>();
                            StringBuilder _dbSql = new StringBuilder("update base_employee set Isauth=1,");
                            _dbSql.AppendFormat("Authtimes='{0}',", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            _dbSql.AppendFormat("wId='{0}'", wechat.WId);
                            _dbSql.AppendFormat(" where EmployeeId='{0}'", emp.EmployeeId);
                            await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);
                            return new { authcode = 1, authmsg = "认证成功", empentity = emp };
                        }
                    }
                    else
                    {
                        return new { authcode = 2, authmsg = "手机号与预留手机号不一致" };
                    }
                }
                else
                {
                    return new { authcode = 0, authmsg = "输入认证手机号有误" };
                }
                #endregion
            }
        }
        #endregion

        #region 获取用户个人信息
        /// <summary>
        /// 获取用户个人信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetEmpInfo")]
        public async Task<dynamic> GetEmpInfo()
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == userInfo.EmployeeId);
                var output = entity.Adapt<EmployeeInfoOutput>();
                output.authTsMenu = output.authMenu == true ? 1 : 0;
                return output;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 获取使用单位
        /// <summary>
        /// 获取可认证使用单位
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetCompanyList")]
        [AllowAnonymous]
        public async Task<dynamic> GetCompanyList()
        {
            StringBuilder dbSql = new StringBuilder("select F_Id as CompanyId,F_FullName as CompanyName,isnull([uni_is],0) as isUseface from [dbo].[base_organize] where F_ParentId='-1' and F_EnabledMark=1 and F_DeleteMark=0 order by F_SortCode");
            return await _db.SqlQueryable<CompanyListOutPut>(dbSql.ToString()).ToListAsync();
        }
        /// <summary>
        /// 获取已认证使用单位
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAuthCompanys")]
        public async Task<dynamic> GetAuthCompanys(string openId)
        {
            return await _db.Queryable<EmployeeWechatEntity>().Where(p => p.IsAudit == 1 && p.IsDeleted == 0 && p.OpenId == openId).ToListAsync();
        }
        #endregion

        #region 临时日志写入
        [NonAction]
        void setlog(string str)
        {
            string name = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            string rootPath = Directory.GetCurrentDirectory();
            string path = $@"{rootPath}/logs/Wechat";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (FileStream fs = new FileStream(path + "/" + name, FileMode.Append))
            {
                str = "\r\n日期：" + DateTime.Now.ToString() + "\r\n消息：" + str;
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(str);
                sw.Flush();
                sw.Close();
            }
        }
        #endregion

        #region 人脸照片_上传
        /// <summary>
        /// 人脸照片_上传
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("FaceBasic64Upload")]
        public async Task<dynamic> FaceBasic64Upload([FromBody] FaceImageInput input)
        {
            var _Output = new FaceImageOutput()
            {
                ret = 0,
                msg = "上传失败"
            };
            try
            {
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
                {
                    string strBase64 = input.fileBase64;
                    string path = App.Configuration["JNPF_App:SystemPath"];
                    var _companyId = "1008";
                    if (!string.IsNullOrEmpty(userInfo.companyId))
                        _companyId = userInfo.companyId;
                    var PhotoPath = path + "faceFile/" + _companyId + "/";
                    if (!Directory.Exists(PhotoPath))
                    {
                        Directory.CreateDirectory(PhotoPath);
                    }
                    var _FileName = userInfo.userId+"_"+DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                    string _FilePath = PhotoPath + _FileName;
                    string base64img = Regex.Replace(strBase64, "data:image/.*;base64,", "");
                    byte[] bytes = Convert.FromBase64String(base64img);
                    FileStream fs = new FileStream(_FilePath, FileMode.CreateNew);
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();
                    var _imgUrl = App.Configuration["JNPF_App:apiBucket"] + "/Resources/faceFile/" + _companyId + "/" + _FileName;
                    _Output = new FaceImageOutput()
                    {
                        
                        ret = 1,
                        msg = "上传成功",
                        fileName = _FileName,
                        imgUrl = _imgUrl
                    };
                    return _Output;
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog("人脸照片_上传,异常,FaceBasic64Upload()->" + ex.Message);
            }
            return _Output;
        }
        #endregion

        #region 人脸认证_20231010
        /// <summary>
        /// 人脸认证
        /// </summary>
        /// <returns></returns>
        [HttpPost("face/register")]
        public async Task<dynamic> faceregister(FaceInput input)
        {
            try
            {
                new LoggEx().uniEvtlog("人脸认证->faceregister()->"+ input.ToJson());
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
                {
                    //new LoggEx().uniEvtlog("人脸认证->faceregister()->1" );
                    var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == userInfo.EmployeeId);
                    if (entity.Isauth > 0)
                    {
                        //new LoggEx().uniEvtlog("人脸认证->faceregister()->2");
                        var _admitGuid = entity.uni_admitGuid;
                        var _dfpOutPut = new dfpOutPut();
                        if (string.IsNullOrEmpty(_admitGuid))
                        {
                            //new LoggEx().uniEvtlog("人脸认证->faceregister()->3");
                            //完成宇泛平台用户注册
                            _dfpOutPut = _uniubiSdkRepository.eyeCreate(entity.JobNum, entity.RealName, entity.CardNo, entity.CompanyId);
                            if (_dfpOutPut != null && _dfpOutPut.result > 0)
                            {
                                var _retdata = (JObject)JsonConvert.DeserializeObject(_dfpOutPut.data);
                                if (_retdata != null)
                                {
                                    _admitGuid = _retdata["admitGuid"].ToString();
                                }
                            }
                        }
                        //new LoggEx().uniEvtlog("人脸认证->faceregister()->4");
                        if (!string.IsNullOrEmpty(_admitGuid))
                        {
                            //new LoggEx().uniEvtlog("人脸认证->faceregister()->5");
                            //直接注册人脸
                            var Paras = new List<SugarParameter>();
                            var _faceUrl = input.FaceUrl;
                            _dfpOutPut = _uniubiSdkRepository.faceRegisterEx(_admitGuid, _faceUrl, entity.CompanyId);
                            if (_dfpOutPut != null )
                            {
                                //new LoggEx().uniEvtlog("人脸认证->faceregister()->6");
                                if (_dfpOutPut.result > 0)
                                {
                                    //new LoggEx().uniEvtlog("人脸认证->faceregister()->7");
                                    var _retdata = (JObject)JsonConvert.DeserializeObject(_dfpOutPut.data);
                                    if (_retdata != null)
                                    {
                                        //new LoggEx().uniEvtlog("人脸认证->faceregister()->8");
                                        var _faceGuid = _retdata["faceGuid"].ToString();
                                        //注册人像成功
                                        StringBuilder _dbSql = new StringBuilder();
                                        _dbSql.Append("update base_employee set ");
                                        _dbSql.AppendFormat(" [uni_is]=1,uni_faceGuid='{0}',uni_faceurl='{1}',uni_admitGuid='{2}'", _faceGuid, input.FaceUrl, _admitGuid);
                                        _dbSql.AppendFormat(" where EmployeeId='{0}'", userInfo.EmployeeId);
                                        _db.Ado.ExecuteCommand(_dbSql.ToString(), Paras);
                                        return new { regcode = 1, regmsg = "注册人脸信息成功" };
                                    }
                                }
                                else
                                {
                                    //new LoggEx().uniEvtlog("人脸认证->faceregister()->9");
                                    return new { ret = 0, code = _dfpOutPut.code, regmsg = "注册人脸信息失败" };
                                }
                            }
                            //new LoggEx().uniEvtlog("人脸认证->faceregister()->10");
                            return new { ret = 0, code ="", regmsg = "注册人脸信息失败" };
                        }
                        else
                        {
                            return new { ret = 0, code = "", regmsg = "添加用户失败" };
                        }
                    }
                    else
                    {
                        return new { ret = 0, code = "", regmsg = "未完成个人信息认证" };
                    }
                }
                else
                {
                    return new { ret = -1, code = "", regmsg = "未登录" };
                }
            }
            catch(Exception ex)
            {
                new LoggEx().errlog("人脸认证,异常,faceregister()->" + ex.Message);
                return new { ret = 0, code = "", regmsg = "注册人脸信息失败" };
            }
        }
        #endregion

        #region 人脸删除_20231010
        /// <summary>
        /// 人脸删除
        /// </summary>
        /// <returns></returns>
        [HttpPost("face/delete")]
        public async Task<dynamic> facedelete()
        {
            try
            {
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserKind == 1 && !string.IsNullOrEmpty(userInfo.EmployeeId))
                {
                    var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == userInfo.EmployeeId);
                    if (!string.IsNullOrEmpty(entity.uni_faceGuid) && !string.IsNullOrEmpty(entity.uni_admitGuid))
                    {
                        //执行删除
                        var _dfpOutPut = _uniubiSdkRepository.faceDelete(entity.uni_admitGuid, entity.uni_faceGuid, entity.CompanyId);
                        if (_dfpOutPut != null)
                        {
                            if (_dfpOutPut.result > 0)
                            {
                                //成功
                                var Paras = new List<SugarParameter>();
                                StringBuilder _dbSql = new StringBuilder();
                                _dbSql.Append("update base_employee set ");
                                _dbSql.Append(" [uni_is]=0,uni_faceGuid='',uni_faceurl=''");
                                _dbSql.AppendFormat(" where EmployeeId='{0}'", userInfo.EmployeeId);
                                _db.Ado.ExecuteCommand(_dbSql.ToString(), Paras);

                                return new { regcode = 1, code = _dfpOutPut.code, regmsg = "删除人脸信息成功" };
                            }
                            else
                                return new { regcode = 0, code = _dfpOutPut.code, regmsg = "删除人脸信息失败" };
                        }
                        else
                        {
                            //失败
                            return new { regcode = 0, code ="", regmsg = "删除人脸信息失败" };
                        }
                    }
                    else
                    {
                        return new { regcode = 0, code = "", regmsg = "未注册人脸信息" };
                    }
                }
                else
                {
                    return new { regcode = -1, code = "", regmsg = "未登录" };
                }
            }
            catch(Exception ex)
            {
                new LoggEx().errlog("人脸删除,异常,facedelete()->" + ex.Message);
                return new { regcode = 0, code = "", regmsg = "删除人脸信息失败" };
            }
        }
        #endregion
    }
}
